package com.example.presentshopping.ui.fragment

import android.Manifest
import android.annotation.SuppressLint
import android.app.Activity
import android.app.Activity.RESULT_OK
import android.app.ActivityOptions
import android.app.Dialog
import android.content.Intent
import android.content.pm.PackageManager
import android.net.Uri
import android.os.Bundle
import android.os.Environment
import android.provider.MediaStore
import android.util.Log
import android.view.Gravity
import android.view.View
import android.widget.LinearLayout
import androidx.core.app.ActivityCompat
import com.bumptech.glide.Glide
import com.example.presentshopping.R
import com.example.presentshopping.config.base.BaseMvpFragment
import com.example.presentshopping.config.base.MyApplication
import com.example.presentshopping.config.bean.SpreadBean
import com.example.presentshopping.config.bean.UserInfoBean
import com.example.presentshopping.exent.ImageVIewExent
import com.example.presentshopping.mvp.presenter.PublicPresenter
import com.example.presentshopping.net.http.HttpRequest
import com.example.presentshopping.net.http.HttpURL
import com.example.presentshopping.net.observer.TaskCallback
import com.example.presentshopping.ui.activity.*
import com.example.presentshopping.ui.custom.CircleImageView
import com.example.presentshopping.ui.dialog.BaseDialog
import com.example.presentshopping.ui.dialog.MenuDialog
import com.example.presentshopping.utils.ToastUtil
import com.example.presentshopping.utils.glide.GlideUtil
import com.example.presentshopping.utils.tool.GsonUtils
import com.example.presentshopping.utils.tool.IntentJumpUtils
import com.example.presentshopping.utils.tool.IntentJumpUtils.startIntent
import com.example.presentshopping.utils.tool.LogUtils
import com.permissionx.guolindev.PermissionX
import com.soundcloud.android.crop.Crop
import kotlinx.android.synthetic.main.fragment_my.*
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import java.io.File
import java.util.*

//个人中心
@Suppress("DEPRECATION")
class MyFragment : BaseMvpFragment() {

    private val SELECT_PICTURE = 0
    private val SELECT_CAMERA = 1
    val CONSULT_DOC_PICTURE = 1000
    val CONSULT_DOC_CAMERA = 1001
    val CORP_CAMERA_IMAGE = 1002
    private val cameraFileUri: Uri? = null
    var userIcon: CircleImageView? = null
    private var queryInfoPresenter: PublicPresenter? = null
    var userInforBean: UserInfoBean? = null
    var spreadBean: SpreadBean? = null
    private var dialogData: List<String>? = null

    //相机拍摄的头像文件(存放在SD卡根目录下) 当前时间+.jpg方式
    private val IMAGE_FILE_NAME = "image_file_name.jpg"

    //类型   1 代表修改生日   2 代表修改头像
    private var type = 0
    override val layoutId: Int
        get() = R.layout.fragment_my

    override fun onResume() {

        if (IntentJumpUtils.isLogin()) {
            // 跳转首页
            oneMyINt()
            myWalletInfo()
        } else {
            // 登录

        }


        super.onResume()
    }

    @SuppressLint("NewApi")
    override fun initView(view: View?, savedInstanceState: Bundle?) {
        queryInfoPresenter = PublicPresenter(context, false, "")
        queryInfoPresenter?.attachView(this)
        userIcon = view?.findViewById(R.id.myself_head)
        EventBus.getDefault().register(this)

        dialogData = ArrayList<String>()
        view?.findViewById<LinearLayout>(R.id.iv_share0)?.setOnClickListener {
            startIntent(context,
                OrderActivity().javaClass)
        }

        view?.findViewById<LinearLayout>(R.id.iv_share1)?.setOnClickListener {
            startIntent(context,
                RqCodeActivity().javaClass)
        }

        view?.findViewById<LinearLayout>(R.id.iv_share2)?.setOnClickListener {
            startIntent(context,
                TeamActivity().javaClass)
        }

        view?.findViewById<LinearLayout>(R.id.iv_share3)?.setOnClickListener {
//            val mIntent = Intent(context, SpreadActivity().javaClass)
//            // mIntent.setClass(this, TransitionActivity::class.java)
//            mIntent.putExtra("transition", "fade")
//            startActivity(mIntent,
//                ActivityOptions.makeSceneTransitionAnimation(activity).toBundle())

            startIntent(context, SpreadActivity().javaClass)

        }

        view?.findViewById<LinearLayout>(R.id.balance_layout_01)?.setOnClickListener {
            startIntent(
                context,
                WalletActivity().javaClass)
        }

        view?.findViewById<LinearLayout>(R.id.iv_share6)?.setOnClickListener {
            startIntent(context,
                LocationActivity().javaClass)
        }

        view?.findViewById<LinearLayout>(R.id.iv_share7)?.setOnClickListener {
            startIntent(context,
                SettingActivity().javaClass)
        }

        view?.findViewById<LinearLayout>(R.id.iv_share8)?.setOnClickListener {
            startIntent(context,
                PromoteOrderActivity().javaClass)
        }

        view?.findViewById<LinearLayout>(R.id.balance_layout_03)?.setOnClickListener {
            startIntent(
                context,
                CumulativeActivity().javaClass)
        }

        view?.findViewById<CircleImageView>(R.id.myself_head)?.setOnClickListener {

//            // 从相册还是 照片选择图片
            (dialogData as ArrayList<String>)?.clear()
            (dialogData as ArrayList<String>)?.add("拍照")
            (dialogData as ArrayList<String>)?.add("从相册中选择")
            showBottonDialog(dialogData!!)


        }


        view?.findViewById<LinearLayout>(R.id.iv_share9)?.setOnClickListener {
            startIntent(
                context,
                StoreListActivity().javaClass)
        }
        //   iv_share6.setOnClickListener { startActivity(Intent(this@SpreadActivity,PromoteOrderActivity().javaClass)) }  // 我的推广订单

    }

    @Subscribe
    fun onEventMainThread(enx: ImageVIewExent) {
        Log.e("onEventMainThread", enx.url)
        onResume()

    }

    fun oneMyINt() {
        Log.e("MyFragment", HttpURL.Req_getUserInfo)
        queryInfoPresenter?.netWorkRequestPost(
            HttpURL.Req_getUserInfo,
            HttpRequest.getGoodsList(1, 1, 1), object : TaskCallback {
                override fun onSuccess(data: String?) {
                    data?.let { Log.e("MyFragment", it) }
                    userInforBean = GsonUtils.getGson().fromJson(data, UserInfoBean().javaClass)
                    vs_myselft_account.text = userInforBean?.data?.mobile
                    data?.let { Log.e("MyFragment", userInforBean?.data?.avatar.toString()) }
                    GlideUtil.load(context, userInforBean?.data?.avatar.toString(), userIcon)
                    MyApplication.userInfoBean = userInforBean
                }

                override fun onFailure(
                    e: Throwable?,
                    code: Int,
                    msg: String?,
                    isNetWorkError: Boolean
                ) {

                }
            }
        )
    }

    fun myWalletInfo() {
        queryInfoPresenter?.netWorkRequestPost(HttpURL.Req_myWalletInfo,
            HttpRequest.getGoodsDetail(""),
            object : TaskCallback {
                override fun onSuccess(data: String?) {
                    spreadBean = GsonUtils.getGson().fromJson(data, SpreadBean().javaClass)
                    //    vs_myselft_account.text = "当前余额： "+

                    balance_textview_01.text = spreadBean?.data?.balance + "元"
                    balance_textview_05.text = spreadBean?.data?.totalWithdrawal.toString()

                }

                override fun onFailure(
                    e: Throwable?,
                    code: Int,
                    msg: String?,
                    isNetWorkError: Boolean
                ) {

                }

            })
    }

    override fun onSuccess(data: String?) {

    }

    override fun onFailure(e: Throwable?, code: Int, msg: String?, isNetWorkError: Boolean) {

    }


    override fun onDestroyView() {
        queryInfoPresenter?.detachView()
        super.onDestroyView()
        EventBus.getDefault().unregister(this)
    }

    /**
     * 选择弹窗
     */
    private fun showBottonDialog(dialogData: List<String>) {
        MenuDialog.Builder(activity)
            .setCancel("取消") // 设置 null 表示不显示取消按钮
            //.setAutoDismiss(false) // 设置点击按钮后不关闭对话框
            .setList(dialogData)
            .setListener(object : MenuDialog.OnListener {
                override fun onSelected(dialog: Dialog?, position: Int, text: String) {
                    if (text == "拍照") {
                        getPicForCamera()
                    } else if (text == "从相册中选择") {
                        // 调用系统打开外部图库程序
                        getPicForLocal()
                    }
                }

                override fun onCancel(dialog: Dialog?) {}
            })
            .setGravity(Gravity.BOTTOM)
            .setAnimStyle(BaseDialog.AnimStyle.BOTTOM)
            .show()
    }

    /**
     * 加载本地相册
     */
    private fun getPicForLocal() {
        // Crop.pickImage(activity, CONSULT_DOC_PICTURE);
        val it = Intent()
        //设置文件类型
        it.type = "image/*"
        it.action = Intent.ACTION_PICK
        startActivityForResult(it, 9999)
    }

    /**
     * 拍照
     */
    private fun getPicForCamera() {
        if (ActivityCompat.checkSelfPermission(context!!,
                Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(
                context!!,
                Manifest.permission.RECORD_AUDIO) != PackageManager.PERMISSION_GRANTED
        ) {
            PermissionX.init(activity)
                .permissions(
                    Manifest.permission.CAMERA,
                    Manifest.permission.WRITE_EXTERNAL_STORAGE,
                    Manifest.permission.READ_EXTERNAL_STORAGE
                )
                .onExplainRequestReason { scope, deniedList ->
                    val message = "PermissionX需要您同意以下权限才能正常使用"
                    scope.showRequestReasonDialog(deniedList, message, "确定", "取消")
                }
                .request { allGranted, grantedList, deniedList ->
                    if (allGranted) {
                        susina()
                    } else {

                    }
                }

        } else {
            susina()
        }

    }
    fun susina(){
        val it = Intent(MediaStore.ACTION_IMAGE_CAPTURE)
        //判断sd卡是否可用,储存照片文件
        if (hasSdcard()) {
            it.putExtra(MediaStore.EXTRA_OUTPUT,
                Uri.fromFile(File(Environment.getExternalStorageDirectory(),
                    IMAGE_FILE_NAME)))
        }
        startActivityForResult(it, 8888)
    }

    /**
     * 检查SD卡是否可用
     */
    private fun hasSdcard(): Boolean {
        val state = Environment.getExternalStorageState()
        //有存储的sdcard
        return state == Environment.MEDIA_MOUNTED
    }

    /**
     * 回调
     *
     * @param requestCode
     * @param resultCode
     * @param data
     */
    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        LogUtils.i("requestCode", "requestCode" + requestCode)
        when (requestCode) {
            8888 -> {
                LogUtils.i("fxx", "拍照")
                //检测手机是否有SD卡
                if (hasSdcard()) {
                    val tempFile = File(Environment.getExternalStorageDirectory(),
                        IMAGE_FILE_NAME)
                    //这个是相机拍摄图片的保存地址
                    val path = Environment.getExternalStorageDirectory().toString()
                    //拍摄图片的图片地址
                    val CAMERA_IMAGE_PATH = "$path/$IMAGE_FILE_NAME"
                    LogUtils.i("fxx", "相机图片地址==$CAMERA_IMAGE_PATH")
                    //头像URI
                    val phoneUri = Uri.fromFile(tempFile)
                    //裁剪图片
                    val time = System.currentTimeMillis()
                    val destination = Uri.fromFile(File(context?.cacheDir,
                        "$time.jpg"))
                    Crop.of(phoneUri, destination).asSquare().start(activity)


                } else {
                    ToastUtil.showMsg("检测到手机没有SD卡存在")
                }
            }
            9999 -> if (data != null) {
                LogUtils.i("fxx", "相册")
                //头像Uri
                val localUri = data.data
                //裁剪图片
                val time = System.currentTimeMillis()
                val destination = Uri.fromFile(File(context?.cacheDir,
                    "$time.jpg"))
                Crop.of(localUri, destination).asSquare().start(activity)
            }
            Crop.REQUEST_CROP -> if (resultCode == RESULT_OK) {

                //裁剪图片uri
                val cropImageUri = Crop.getOutput(data)
                LogUtils.i("requestCode", "resultCode$data")
                LogUtils.e("requestCode", "裁剪成功    图片地址=" + cropImageUri.path)

                userIcon?.let { Glide.with(this).load(cropImageUri).into(it) }
                //设置类型


                //执行上传图片操作
                //uploadImage(cropImageUri)
            }
            else -> {
            }
        }
    }
}
